import jwt 
import time
import logging
from comp_test.settings import SECRET_KEY
"""
过期时间：3600秒(60分钟)，采用django自带的盐值作为密钥
"""
def get_token(user): 
    token = jwt.encode({'expir': time.time()+3600, 'user_id': str(user.id)}, #将数据库中uuid对象转为str类型
                       SECRET_KEY, algorithm='HS256', headers={'alg': 'HS256'}).decode('ascii')
    return token


def access_log(func):
    logger = logging.getLogger(__name__)
    logger.setLevel(level=logging.INFO)  #日志级别
    handler = logging.FileHandler("log.txt")  #日志文件位置
    handler.setLevel(logging.INFO)
    formatter = logging.Formatter(
        '%(asctime)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    def inner(request, *args):
        """
        通过请求头同获取各个参数，并写进log
        """
        mydict={"POST":request.POST,"GET":request.GET}
        method = request.META.get('REQUEST_METHOD')  #请求方法
        path = request.META.get('PATH_INFO')  #接口路径
        ip = request.META.get('REMOTE_ADDR')  #ip地址
        user_ = request.META.get('HTTP_USER_AGENT')  #user
        parames = mydict[str(request.META.get('REQUEST_METHOD'))]  #参数
        blank = '\000'*2
        logger.info(method+blank+path+blank+ip+blank+user_+blank+str(parames))  #存入信息
        res = func(request,*args)
        return res

    return inner
